<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * Output class
 */
class Output {
	private static $_instance = null;
	protected $_header = array();
	protected $_body = array();
	protected $_status = 200;
	protected $_statuses = array(
		200 => 'OK',
		301 => 'Moved Permanently',
		302 => 'Found',	
		404 => 'Not Found',
		503 => 'Service Unavailable'
	);

	public static function &instance() {
		if (!isset(self::$_instance)) {
			$c = __CLASS__;
			self::$_instance = new $c;
		}

		return self::$_instance;
	}

	private function __construct() {}

	public function __clone() {
		throw new Node_Exception('Can`t clone singletone object');
	}

	public static function body($cont) {
		self::instance()->_body[] = $cont;
    }

	public static function header($cont) {
		self::instance()->_header[] = $cont;
	}

	public static function status($code) {
		$code = intval($code);
		if ($code > 0) {
			$output = self::instance();
			if (array_key_exists($code, $output->_statuses)) { 
				$output->_status = $code;
			}
		}
	}

	/**
	 * Send headers
	 */
	public static function sendHeaders() {
		$output = self::instance();

		$http_string = 'HTTP/1.1 ' . $output->_status . ' ' . $output->_statuses[$output->_status];
		header($http_string, true, $output->_status);
		
		foreach ($output->_header as $header) {
			header($header);
		}
	}

	/**
	 * Rendering body
	 */
	public static function renderBody() {
		$output = self::instance();

		$body = '';
		foreach ($output->_body as $body_item) {
			$body .= strval($body_item);
		}

		// Cache output body if needed
		if (Config::get('perform_output_caching', 'cache', false)) {
			$cache_key = Router::getUniqueKey();
			Cache::set($cache_key, $body, Config::get('output_ttl', 'cache', 86400));
		}

		echo $body;
	}
}
